package com.enjoy.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.enjoy.config.FileConfig;
import com.enjoy.config.MinioConfig;
import com.enjoy.domain.SubImageInfo;
import com.enjoy.domain.SubImageInfoObject;
import com.enjoy.domain.VdsFace;
import com.enjoy.factory.TimeFormatFactory;
import com.enjoy.util.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 人脸对象接口
 *
 * @author 1h
 */
@Slf4j
@RestController
public class FaceController {

    @Autowired
    private FileConfig fileConfig;
    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private MinioUtil minioUtil;

    /**
     * 批量新增人脸
     */
    @PostMapping(value = "/Faces")
    public String faces(@RequestBody String faceInfo) {
        JSONObject responseStatusListObject = new JSONObject();
        JSONObject responseStatusObject = new JSONObject();
        SimpleDateFormat sdf = TimeFormatFactory.getSimpleDateFormat();
        JSONArray jsonArray = new JSONArray();
        JSONObject jp = (JSONObject) JSONObject.parse(faceInfo);
        String deviceID = "";
        jp = jp.getJSONObject("FaceListObject");
        JSONArray faceObject = jp.getJSONArray("FaceObject");
        String nowTime = sdf.format(new Date());
        for (Object object : faceObject) {
            JSONObject jsonObject = (JSONObject) object;
            VdsFace face = JSON.parseObject(jsonObject.toString(), VdsFace.class);
            deviceID = face.getDeviceID();
            // 生成本地图片
            SubImageInfoObject subImageList = face.getSubImageList();
            if (subImageList != null && subImageList.getSubImageInfoObject().size() > 0) {
                for (SubImageInfo subImageInfo : subImageList.getSubImageInfoObject()) {
                    generateImage(subImageInfo.getData(), fileConfig.getProfile() + "\\" + deviceID + "\\" + nowTime + "\\", subImageInfo.getImageID() + ".jpg");
                    // 上传minIO
                    storageFile(fileConfig.getProfile() + "\\" + deviceID + "\\" + nowTime + "\\", subImageInfo.getImageID() + ".jpg");
                }
            }
            /*log.info("json: ", faceInfo);
            log.info("解析结果：" + face);
            log.info("设备ID：" + deviceID);*/
            JSONObject jo = new JSONObject();
            jo.put("Id", face.getFaceID());
            jo.put("StatusCode", "0");
            jo.put("RequestURL", "/VIID/Faces");
            jo.put("StatusString", "OK");
            SimpleDateFormat sdfTime = TimeFormatFactory.getSimpleDateFormat();
            jo.put("LocalTime", sdfTime.format(new Date()));
            TimeFormatFactory.addSimpleDateFormat(sdfTime);
            jsonArray.add(jo);
        }
        responseStatusObject.put("ResponseStatusObject", jsonArray);
        responseStatusListObject.put("ResponseStatusListObject", responseStatusObject);
        log.info(responseStatusListObject.toString());
        return responseStatusListObject.toJSONString();
    }

    /**
     * 对字节数组字符串进行Base64解码并生成图片
     */
    private static boolean generateImage(String imgStr, String imgFilePath, String imgFileName) {
        if (imgStr == null) {
            // 图像数据为空
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            File file = new File(imgFilePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                // 调整异常数据
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath + imgFileName);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * MinIO文件上传
     */
    public Boolean storageFile(String filePath, String fileName) {
        // 首先判断是否存在该bucketName
        Boolean flag = minioUtil.bucketExists(minioConfig.getBucketName());
        // 不存在就创建
        if (!flag) {
            // 创建bucketName
            minioUtil.makeBucket(minioConfig.getBucketName());
        }
        // 生成文件名
        String newFileName = DateFormatUtils.format(new Date(), "yyyy/MM/dd")
                + "/" + fileName;
        // 文件上传
        return minioUtil.upload2(new File(filePath + fileName), newFileName, minioConfig.getBucketName());
        // 上传成功的文件路径
        //String url = minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
    }

}
